<template>
  <div style="padding:0 37px 0 44px">
    <div class="breadcrumb-father">
      <div class="new-breadcrumb">
        <router-link  :to="{path:'/welcome'}">
          <img src="../../../assets/imgs/Home.png" alt="">
        </router-link>
        <router-link :to="{path:'/firm'}">{{$t('mer.firm')}}</router-link>
        <span class="arrow">></span>
        
        <span :title="$route.query.name">{{$route.query.name}}</span>
      </div>
    </div>

    <div class="handle_box">
        <ul class="button_box" v-if="userType!=='9' && userType !== '11' && userType !== '5' && showHandle ">
            <li class="confirm" v-if='isModify' @click='modify()'>
                <icon-svg icon-class="xiugai" class="icon-btn"></icon-svg>{{$t('button.Modify')}}
            </li>
            <li class="confirm" v-if='isAdd' @click="addFirm()">
                <icon-svg icon-class="tijiao" class="icon-btn"></icon-svg>{{ $t('button.OK') }}
            </li>
            <li class="confirm" v-show='showBtn' @click='commitModify()'>
                <icon-svg icon-class="tijiao" class="icon-btn"></icon-svg>{{ $route.query.state == '0' ? $t('button.Resubmit') : $t('button.OK') }}
            </li>
            <li class="cancel" v-show='!showDetails' @click="reset()">
                <icon-svg icon-class="quxiao" class="icon-btn"></icon-svg>{{$t('button.Cancel')}}
            </li>
        </ul><!-- button_box结束 -->
    </div><!-- handle_box结束 -->

    <!-- 防止表格层被遮挡 -->
    <div class="table-space-div"></div>

    <div class="table-div">
      <div class="title">{{$t('agent.CompanyInfo')}}</div>
      <ul class="content">
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.Name')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="firmData.name" id="name" type="text" :readonly="showDetails" maxlength="100" @blur="checkName" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.Type')}}:</div>
          </div>
          <div class="right-div">
            <input v-show="showDetails" v-model="firmData.idType" type="text" :readonly="showDetails" :class="{'view-input': showDetails}" />

            <el-select v-show="!showDetails" :placeholder="$t('placeH.Please')" v-model.lazy="firmData.idType" clearable :readonly="showDetails">
              <el-option :value="$t('mer.LimitedCompany')"></el-option>
              <el-option :value="$t('mer.Partnership')"></el-option>
              <el-option :value="$t('mer.SoleProprietor')"></el-option>
            </el-select>
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.Address')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="firmData.address" id="address" type="text" :readonly="showDetails" maxlength="200" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.MailAddr')}}:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="firmData.mailingAddress" type="text" :readonly="showDetails" maxlength="200" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('mer.BRNo')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="firmData.registrationNumber" id="registrationNumber" type="text" :readonly="showDetails" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\-]/g,'')" maxlength="20" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.Contact')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="firmData.contacts" id="contacts" type="text" :readonly="showDetails" maxlength="50" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont" v-if="companyId=='2'">{{$t('mec.Email')}}*:</div>
            <div class="cont" v-else>{{$t('mec.Email')}}:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="firmData.email" id="email" :readonly="showDetails" maxlength="100" @blur="valiEmail()" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont" >{{$t('agent.PhoneNo')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="firmData.phone" id="phone" type="text" @blur="checkPhone" :readonly="showDetails" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\-]/g,'')" maxlength="20" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.MobileNo')}}*:</div>
          </div>
          <div class="right-div">
              <input v-model.lazy.trim="firmData.telephone" id="telephone" type="text" :readonly="showDetails" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\-]/g,'')" maxlength="20" :class="{'view-input': showDetails}" />
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('search.UpperLevel1')}}*:</div>
          </div>
          <div class="right-div">
            <input v-model="firmData.parentDistributorName" id="parentDistributorName" type="text" :readonly="showDetails" v-show="showDetails" :class="{'view-input': showDetails}" />

            <el-select v-show="!showDetails" v-model.lazy="firmData.parentDistributorName" @change='selectId()' clearable :placeholder="$t('placeH.Please')" :readonly="showDetails">
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.UpperLevelID')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="firmData.parentDistributorNumber" id="parentDistributorNumber" type="text" disabled="true" :class="{'view-input': showDetails}" /></div>
        </li>
      </ul><!-- content结束 -->
      <!-- <div class="circle-title">Shop photos</div> -->
    </div><!-- table-div结束 -->

  </div>
</template>
<script>
import { handleFirm,queryFirmDel,checkFirmName,checkPhoneForFirm,reauditViceFirm } from "api/firm/index";
import { querySuperiorAgent, } from "api/merchant/agent/index";
export default {
  
  data() {
    return {
      companyId:localStorage.getItem('companyId'),
      userType:localStorage.getItem('userType'),
      userPhone:localStorage.getItem('phone'),
      isAdd: this.$route.query.id == '1' ? true : false, //新增按钮显示或隐藏 根据父组件传递的id判断
      isModify: this.$route.query.id == '2' ? true : false, //修改按钮显示或隐藏 根据父组件传递的id判断
      showDetails: this.$route.query.id == '1' ? false : true,
      showBtn: false,
      firmData:{
        name: undefined,
        idType: undefined,
        address: undefined,
        mailingAddress: undefined,
        registrationNumber: undefined,
        contacts: undefined,
        email: undefined,
        phone: undefined,
        telephone: undefined,
        parentDistributorName:undefined,
        parentDistributorNumber:undefined,
      },
      HkAgentRequiredArr: [
        "name",
        "address",
        "registrationNumber",
        "contacts",
        "phone",
        "telephone",
        "parentDistributorName",
      ],
      requiredArr:[],
      flag: false,
      modifyFlag:false,
      options:[],
      selAgentObj:{},
      selDistributorId: localStorage.getItem("distributorId"),
      grade: localStorage.getItem("grade"),
      showHandle: true,
    };
  },
  created() {
    if (this.$route.query.state == "0") {
      this.isModify = false;
    }
    if (this.$route.query.id == '2') {
      this.getFirmDetails(this.$route.query.firmId);
    }
    if (this.userType == "2" && this.grade != '0' ) {
      this.selAgentObj.distributorId = this.selDistributorId;
      this.getSuperiorAgent(this.selAgentObj);
    } else {
      this.selAgentObj.companyId = this.companyId;
      this.getSuperiorAgent(this.selAgentObj);
    }

    $("#z_businessManagement .el-menu a li:eq(2)").addClass('is-active');
  },
  beforeRouteLeave(to,from, next){
    if(to.path == '/firm'){
      next();
    } else {
      $("#z_businessManagement .el-menu a li:eq(2)").removeClass('is-active');
      localStorage.removeItem('queryFirmData');
      next();
    }
  },
  updated(){
    $(".border-red").removeClass('border-red');
  },
  methods: {
    // 选择上级代理商
    selectId() {
      for (let i = 0; i < this.options.length; i++) {
        if (this.options[i].name == this.firmData.parentDistributorName) {
          this.firmData.parentDistributorId = this.options[i].id;
          this.firmData.parentDistributorNumber = this.options[i].distributorNumber;
        }
      }
    },
    // 查询上级代理商
    getSuperiorAgent(data) {
      querySuperiorAgent(data).then(res => {
        //          console.log(res);
        this.options = res.value.filter(function(item,index,array){
          return (item.grade != 0);
        })
      });
    },
    // 公司详情
    getFirmDetails(firmId) {
      queryFirmDel(firmId).then(res => {
          // console.log("----该公司详情---");
          // console.log(res);
          this.firmData = res.value;
          if( this.$route.query.id == '2' && this.userType == "2" ){
            this.showHandle = this.firmData.firmId ==  this.$route.query.firmId ? true : false;
            if( this.grade == 0 ){
              this.showHandle = true;
            }
          }
        })
        .catch(error => {});
    },
    //公司修改确定按钮
    commitModify() {
      const _that = this;
      [...this.requiredArr] = this.HkAgentRequiredArr;
      const reg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/; 
      if(this.firmData.email){
        if( !reg.test(this.firmData.email) ){
          this.$message( this.$t('hint.EmailFormatIncorrect') );
          return false;
        }
      }
      for (let i = 0; i < this.requiredArr.length; i++) {
        if ( this.firmData[this.requiredArr[i]] == "" || this.firmData[this.requiredArr[i]] == null || this.firmData[this.requiredArr[i]] == undefined ) {
          let prer_html = $("#" + _that.requiredArr[i]).parent().prev().children().html();
          if(localStorage.getItem('locale') == 'en' ){
            prer_html = prer_html.replace('*','').toLocaleLowerCase();
          } else {
            prer_html = prer_html.replace('*','');
          }         
          $("#" + _that.requiredArr[i]).addClass('border-red');
          this.$message( this.$t('hint.pleaseEnter') + prer_html );
          return false;
        } else {
          this.modifyFlag = true;
        }
      }
      if(this.modifyFlag){
        if (this.$route.query.state == "0") {
          this.firmData.state = 4;
        }
        const hintAgentMsg = 
          this.$route.query.state == "0"
            ? this.$t('hint.SureToAddThisCompany')
            : this.$t('hint.confirmToMakeTheChanges');
        this.$msgbox({
          title: this.$t("hint.Alert"),
          message: hintAgentMsg,
          showClose: false,
          closeOnClickModal:false,
          showCancelButton: true,
          confirmButtonText: this.$t("button.OK"),
          cancelButtonText: this.$t("button.Cancel")
        })
          .then(() => {
            this.firmData.remarks = 1;
            const func = this.firmData.state == '2' ? reauditViceFirm : handleFirm;
            this.firmData.remarks = this.firmData.state == '2' ? 0 : 1;
            func(this.firmData).then(res => {
              this.modifyFlag = false;
              if (res.code == 0) {
                this.$msgbox({
                  title: this.$t("hint.Alert"),
                  message: this.$t("hint.SubmittedApprovalPending"),
                  showClose: false,
                  closeOnClickModal:false,
                  showCancelButton: false,
                  confirmButtonText: this.$t("button.OK"),
                  cancelButtonText: this.$t("button.Cancel"),
                  customClass:'single-msg-box',
                }).then(() => {
                    this.$router.push({ path: "/firm" });
                  })
                  .catch(() => {
                    this.firmData = res.value;
                  });
              } else {
                this.$notify({
                  title: this.$t("hint.Fail"),
                  message: this.$t("hint.FailToEdit"),
                  type: "error",
                  duration: 2000
                });
              }
            });
          })
          .catch(() => {
            done();
          });
      }
    },
    // 新增公司
    addFirm() {
      const _that = this;
      [...this.requiredArr] = this.HkAgentRequiredArr;
      for (let i = 0; i < this.requiredArr.length; i++) {
        if ( this.firmData[this.requiredArr[i]] == "" || this.firmData[this.requiredArr[i]] == null || this.firmData[this.requiredArr[i]] == undefined ) {
          let prer_html = $("#" + _that.requiredArr[i]).parent().prev().children().html();
          if(localStorage.getItem('locale') == 'en' ){
            prer_html = prer_html.replace('*','').toLocaleLowerCase();
          } else {
            prer_html = prer_html.replace('*','');
          }
          // console.log($("#" + _that.requiredArr[i]));  
          $("#" + _that.requiredArr[i]).addClass('border-red');
          this.$message( this.$t('hint.pleaseEnter') + prer_html );
          return false;
        }
      }
      const reg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
      if( this.firmData.email ){
        if( !reg.test(this.firmData.email) ){
          this.$message( this.$t('hint.EmailFormatIncorrect') );
          return false;
        } else {
          this.flag = true;
        }
      } else {
        this.flag = true;
      }
      if (this.flag) {
        this.$msgbox({
          title: this.$t("hint.Alert"),
          message: this.$t('hint.SureToAddThisCompany'),
          showClose: false,
          closeOnClickModal:false,
          showCancelButton: true,
          confirmButtonText: this.$t("button.OK"),
          cancelButtonText: this.$t("button.Cancel")
        }).then(() => {
          this.firmData.remarks = 0;
          this.firmData.companyId = this.companyId;
          handleFirm(this.firmData).then(res => {
            this.flag = false;
              if (res.code == 0) {
                this.$notify({
                  title: this.$t("hint.Success"),
                  message: this.$t("hint.CreateOK"),
                  type: "success",
                  duration: 2000
                });
                this.$router.push({ path: "/firm" });
              } else {
                this.$notify({
                  title: this.$t("hint.Fail"),
                  message: this.$t("hint.CreateFailed"),
                  type: "error",
                  duration: 2000
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        });
      }
    },
    // 修改按钮
    modify() {
      this.showDetails = false;
      this.showBtn = true;
      this.isModify = false;
      localStorage.setItem('firmData',JSON.stringify(this.firmData));
    },
    // 取消按钮
    reset(){
      if(this.$route.query.id=='2'){
        this.showDetails = true;
        this.showBtn = false;
        this.isModify = true;
        this.firmData = JSON.parse(localStorage.getItem('firmData'));
      } else {
        this.$router.push({ path: "/firm" });
      }
    },
    // 验证公司名称
    checkName(){
      if(!this.firmData.name) return false;
      if(this.$route.query.id == '1'){
        checkFirmName({name:this.firmData.name,companyId:this.companyId,}).then(res=>{ 
          if( res.code == 0 ){
            return false;
          } else {
            this.$message( this.$t('hint.CompanyNameAlreadyExists') );
            this.firmData.name = '';
          }
        })
      } else {
        checkFirmName({name:this.firmData.name,companyId:this.companyId,firmId:this.firmData.firmId}).then(res=>{ 
          if(res.code == 0){
            return false;
          } else {
            this.$message( this.$t('hint.CompanyNameAlreadyExists') );
            this.firmData.name = '';
          }
        })
      }
    },
    // 验证公司座机
    checkPhone(){
      if( this.firmData.phone == undefined || this.firmData.phone == '') return false;
      if(this.$route.query.id == '1'){
        checkPhoneForFirm({phone:this.firmData.phone}).then(res=>{
          if(res.code == 0){
            return false;
          } else {
            this.$message( this.$t('hint.PhoneNumberAlreadyExists1') );
            this.firmData.phone = '';
          }
        })
      } else {
        checkPhoneForFirm({phone:this.firmData.phone,userId:this.firmData.userId}).then(res=>{
          if(res.code == 0){
            return false;
          } else {
            this.$message( this.$t('hint.PhoneNumberAlreadyExists1') );
            this.firmData.phone = '';
          }
        })
      }
      
    },
    // 验证邮箱格式
    valiEmail(){
      const reg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
      if( !this.firmData.email ){
        return false;
      } else if( !reg.test(this.firmData.email) ){
          this.$message( this.$t('hint.EmailFormatIncorrect') );
          return;
      } 
    },
  }
};
</script>

<style lang="scss" scoped>
.border-red{
  border:1px solid red;
}
</style>
